package cn.com.woxitech.dev.controller.mvc;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.EncryptionUtils;
import cn.com.woxitech.dev.common.StrUtils;
import cn.com.woxitech.dev.common.weixin.PayCommonUtil;
import cn.com.woxitech.dev.common.weixin.XMLUtil;
import cn.com.woxitech.dev.model.WeixinWebAccessToken;
import cn.com.woxitech.dev.model.gen.WmLecture;
import cn.com.woxitech.dev.model.gen.WmLecturePage;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.UserService;
import cn.com.woxitech.dev.service.WeixinService;

@Controller
public class WebMVCController {
	
	@Autowired 
	private WeixinService weixinService;
	
	@Autowired 
	private UserService userService;
	
	@Autowired
	private RoomService roomService;
	@Autowired
	private LectureService lectureService;
	@Autowired
	private LecturePageService lecturePageService;
	
	@RequestMapping(value="/mvc/authorize_direct",method=RequestMethod.GET)
	public ModelAndView weixin_authorize_direct(HttpServletRequest request){
		String state = request.getParameter("state");
		String authorize_callback = "/mvc/authorize_callback";
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		String view = "";//"redirect:http://www.baidu.com";
		
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
				+ Const.APPID
				+ "&redirect_uri="
				+ Const.SERVER_BASE + authorize_callback
				+ "&response_type=code&scope=snsapi_base&state="
				+ state //"/attend/room_uuid/12345"
				+ "#wechat_redirect"; 
				
		view = "redirect:"	+ url;
		
		return new ModelAndView(view).addAllObjects(map);
	}
	
	@RequestMapping(value="/mvc/authorize",method=RequestMethod.GET)
	public ModelAndView weixin_authorize(HttpServletRequest request){
		String state = request.getParameter("state");
		String authorize_callback = "/mvc/authorize_callback";
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		String view = "";//"redirect:http://www.baidu.com";
		
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
				+ Const.APPID
				+ "&redirect_uri="
				+ Const.SERVER_BASE + authorize_callback
				+ "&response_type=code&scope=snsapi_userinfo&state="
				+ state //"/attend/room_uuid/12345"
				+ "#wechat_redirect"; 
				
		view = "redirect:"	+ url;
		
		return new ModelAndView(view).addAllObjects(map);
	}
	
	
	@RequestMapping(value="/mvc/authorize_callback",method=RequestMethod.GET)
	public ModelAndView authorize_callback(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		String view = "";
		
		String code = request.getParameter("code");
		String state = request.getParameter("state"); //跳转到node3什么页面
		WeixinWebAccessToken access_token = new WeixinWebAccessToken();
		try {
			access_token = weixinService.getWeixinWebAccessToken(code);
			WmUser wmUser = userService.saveWeixinWebAccessToken(access_token);
			if(wmUser.getNeedUpdate().equals("3")){
				wmUser = weixinService.getUserInfoFromWeiXin(wmUser);
				wmUser.setNeedUpdate("1");
				userService.updateUserByUuid(wmUser, wmUser.getUuid());
			}
			
			
			view = "redirect:"	+ Const.FRONTWEB_SERVER_BASE + state + "?unionid=" + wmUser.getWxUnionid();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			if(e.getMessage().equals("invalid_code")){
				//invalid code
				
			}
			e.printStackTrace();
			
			String authorize_callback = "/mvc/authorize_callback";
			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
					+ Const.APPID
					+ "&redirect_uri="
					+ Const.SERVER_BASE + authorize_callback
					+ "&response_type=code&scope=snsapi_userinfo&state="
					+ state //"/attend/room_uuid/12345"
					+ "#wechat_redirect"; 
					
			view = "redirect:"	+ url;
		}
		
		return new ModelAndView(view).addAllObjects(map);
	}
	
	@RequestMapping(value = "/mvc/qrcode/luyanlogincallback", method = RequestMethod.GET)
	public ModelAndView qrcodeluyanlogin(HttpServletRequest request, HttpServletResponse reponse) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		
//		state = "http://139.129.205.121:28080/admin-index.html";
//		String view = "redirect:http://139.129.205.121:28080/admin-index.html?encry=";
		String view = "redirect:"+state+"?encry=";
		
		//通过code换取access_token
		WeixinWebAccessToken wwat = this.weixinService.getWeiXinUserByOpenAPICode(code);
		
//		{
//		"access_token":"OezXcEiiBSKSxW0eoylIeLiF1zeO_44joSNNw4KUCyBG8YIfw_IZokXqKABHRPEJonOI6yujJMp59KoY8T4ZJiZrzMFX_2_t8UMNPajmgqQT0wbFJArcgZ4nnhRNAxGyaICisZgAoy4VVKgHkklRRA",
//		"expires_in":7200,
//		"refresh_token":"OezXcEiiBSKSxW0eoylIeLiF1zeO_44joSNNw4KUCyBG8YIfw_IZokXqKABHRPEJ-JPeLsUQGwH9aXAJUWv8Nk5mliwn0ojuWhXD5uk6reHF13oX0cLAKSuVOdLn6gjTvxjGSdSrDut2NwNt1Apb1w",
//		"openid":"obALMwrhppTO-IYvLpSVJ9NhgxWw",
//		"scope":"snsapi_login",
//		"unionid":"o9SI3t5zIxt0rkk9_4w8AshIJcWI"
//	    }
		
//		?unionid=o9SI3t5zIxt0rkk9_4w8AshIJcWI&time=1470196134820
		String unionid = wwat.getUnionid();
		long now = System.currentTimeMillis();
		String key = "?unionid="+unionid+"&time="+now;
		key = EncryptionUtils.encode(key);
		view = view + key;
		
		return new ModelAndView(view,map);
	}

	@RequestMapping(value = "/mvc/qrcodeLogin_callback", method = RequestMethod.GET)
	public ModelAndView qrcodelogin(HttpServletRequest request, HttpServletResponse reponse) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		String view = "redirect:"+Const.FRONTWEB_SERVER_BASE + "/pptupload";
		
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		
		//通过code换取access_token
		WeixinWebAccessToken wwat = this.weixinService.getWeiXinUserByOpenAPICode(code);
		
		WmUser wmUser = this.userService.getUserByUnionId(wwat.getUnionid());
		
		if(wmUser == null){
			//从来没有用过微讲堂的用户 -> 生成login页面的二维码供用户扫描
			view = "redirect:"+Const.FRONTWEB_SERVER_BASE + "/noteverlogined";
			
		}else{
			
			String unionid = wwat.getUnionid();
			String param_org = "?unionid="+unionid + "&time="+System.currentTimeMillis();
			String param = "?encry="+EncryptionUtils.encode(param_org);
			
			view = view + param;
			
			wmUser.setOpenAccessToken(wwat.getAccess_token());
			wmUser.setOpenRefreshToken(wwat.getRefresh_token());
			wmUser.setOpenOpenid(wwat.getOpenid());
			
			this.userService.updateUser(wmUser);
			
		}
		
//		{
//		"access_token":"OezXcEiiBSKSxW0eoylIeLiF1zeO_44joSNNw4KUCyBG8YIfw_IZokXqKABHRPEJonOI6yujJMp59KoY8T4ZJiZrzMFX_2_t8UMNPajmgqQT0wbFJArcgZ4nnhRNAxGyaICisZgAoy4VVKgHkklRRA",
//		"expires_in":7200,
//		"refresh_token":"OezXcEiiBSKSxW0eoylIeLiF1zeO_44joSNNw4KUCyBG8YIfw_IZokXqKABHRPEJ-JPeLsUQGwH9aXAJUWv8Nk5mliwn0ojuWhXD5uk6reHF13oX0cLAKSuVOdLn6gjTvxjGSdSrDut2NwNt1Apb1w",
//		"openid":"obALMwrhppTO-IYvLpSVJ9NhgxWw",
//		"scope":"snsapi_login",
//		"unionid":"o9SI3t5zIxt0rkk9_4w8AshIJcWI"
//	    }
		return new ModelAndView(view,map);
	}
	
	
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public ModelAndView test(HttpServletRequest request, HttpServletResponse reponse) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		String view = "test";
		
		
		Cookie cookie = new Cookie("unionid2","abc");
//		oItem.setDomain(.google.com);  //请用自己的域  
//cookie.setMaxAge(-1); //关闭浏览器后，cookie立即失效          
		reponse.addCookie(cookie);
		
		return new ModelAndView(view,map);
	}
	
	@RequestMapping(value = "/inlineplayer", method = RequestMethod.GET)
	public ModelAndView inlineplayer(HttpServletRequest request, HttpServletResponse reponse) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		String view = "inlineplayer";
		
		String roomuuid = request.getParameter("room");
		
		WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
		
		WmLecture lecture = this.lectureService.getLectureByRoomUuid(room.getUuid());
		
		WmLecturePage lecutre_page = this.lecturePageService.getFirstLecturePageByLectureUuid(lecture.getUuid());
		
		map.put("pageurl", lecutre_page.getPageurl());
		map.put("thumburl", lecutre_page.getThumburl());
		
		return new ModelAndView(view,map);
	}

	@RequestMapping(value = "/mvc/snapshot_cover/{roomuuid}")
	public ModelAndView snapshot_cover(@PathVariable String roomuuid){
		Map<String, Object> map = new HashMap<String, Object>();
		String view = "redirect:";
		
		String key = "snapshot_"+roomuuid;
		
		String url = "http://qiniucdn.haojs.com.cn/"+key;
		
		url = url + "?t="+System.currentTimeMillis();
		view = view + url;
		
		return new ModelAndView(view,map);
	}
	
	@RequestMapping(value = "/mvc/weixinpay/zbskd/notify")
	public ModelAndView weixinpay_notify(HttpServletRequest request){
		Map<String, Object> mapH = new HashMap<String, Object>();
		String view = "";
		view = "weixinpay_black";
		String app = "2"; //zbskd
		String content ="";
		try {
			
	        String res = StrUtils.Inputstr2Str_Reader(request.getInputStream(),"utf-8");
	        
	        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
			Map<String, String> map = new HashMap();
			map = XMLUtil.doXMLParse(res);
				
			Set set = map.entrySet();        
			Iterator i = set.iterator();        
			while(i.hasNext()){     
			     Map.Entry<String, String> entry1=(Map.Entry<String, String>)i.next();   
			     if(!entry1.getValue().equals("sign")){
				     parameters.put(entry1.getKey(), entry1.getValue());			    	 
			     }
			}   
			
//			appid
			String APIKEY = Const.ZBSKD_MCH_SECRETKEY;
			
			String sign_orig = PayCommonUtil.createSign2("UTF-8", parameters,APIKEY);
			
			if(sign_orig.equals(map.get("sign"))){
				content = "<xml>"
						+ "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>"
						+ "</xml>";
				
				//TODO: 
				//记录到自己的数据库中或者发送短信通知
				
			}else{
				content = "<xml>"
						+ "<return_code><![CDATA[FAILED]]></return_code>"
						+ "<return_msg><![CDATA[sign is incorrect]]></return_msg>"
						+ "</xml>";
			}
			
	        mapH.put("htmlText", content);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			content = "<xml>"
					+ "<return_code><![CDATA[FAILED]]></return_code>"
					+ "<return_msg><![CDATA[sign is incorrect]]></return_msg>"
					+ "</xml>";
		}
		
		return new ModelAndView(view,mapH);
	}
	
}
